<!-- src/views/RegisterView.vue -->
<template>
  <div class="login-container">
    <el-card class="login-card" shadow="never">
      <template #header>
        <h2 class="login-title">用户注册</h2>
      </template>

      <el-form :model="formData" :rules="rules" ref="formRef" class="login-form" @submit.prevent="onSubmit">
        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="formData.username"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="formData.phone"
            placeholder="请输入11位手机号"
            clearable
          />
        </el-form-item>

        <!-- 密码 -->
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="至少6位字符"
            clearable
            show-password
          />
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="formData.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            clearable
            show-password
          />
        </el-form-item>

        <!-- 居住城市选择（籍贯） -->
        <el-form-item label="居住城市" prop="cityId">
          <el-row :gutter="10">
            <el-col :span="12">
              <el-select
                v-model="formData.provinceId"
                placeholder="请选择省份"
                clearable
                filterable
                @change="onProvinceChange"
                style="width: 100%;"
              >
                <el-option
                  v-for="province in provinces"
                  :key="province.id"
                  :label="province.name"
                  :value="province.id"
                />
              </el-select>
            </el-col>
            <el-col :span="12">
              <el-select
                v-model="formData.cityId"
                placeholder="请选择城市"
                clearable
                filterable
                :disabled="!formData.provinceId"
                style="width: 100%;"
              >
                <el-option
                  v-for="city in cities"
                  :key="city.id"
                  :label="city.name"
                  :value="city.id"
                />
              </el-select>
            </el-col>
          </el-row>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" native-type="submit" class="submit-btn" :loading="loading">
            {{ loading ? '注册中...' : '注 册' }}
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 其他链接 -->
      <div class="login-links">
        <el-link type="primary" @click="gotoLogin">已有账号？去登录</el-link>
        <el-link type="success" @click="gotoForget">忘记密码？</el-link>
      </div>
    </el-card>
  </div>
  <app-footer></app-footer>
</template>

<script setup>
import '@/assets/styles/login-common.css';// 局部导入样式文件
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { defineEmits } from 'vue'
import AppFooter from '@/components/Footer/Footer.vue'
import { register, getProvinceList, getCityList } from '@/api/user'

const emit = defineEmits(['to-login', 'to-forget', 'close'])

const formRef = ref(null)
const router = useRouter()

// 表单数据
const formData = reactive({
  username: '',
  phone: '',
  password: '',
  confirmPassword: '',
  provinceId: null,
  cityId: null
})

// 省份和城市数据
const provinces = ref([])
const cities = ref([])

// 加载省份列表
const loadProvinces = async () => {
  try {
    const provinceData = await getProvinceList()
    // 只显示状态为1（启用）的省份
    provinces.value = provinceData.filter(province => province.status === 1)
  } catch (error) {
    ElMessage.error('加载省份列表失败: ' + error.message)
  }
}

// 加载城市列表
const loadCities = async (provinceId) => {
  try {
    const cityData = await getCityList(provinceId)
    // 只显示状态为1（启用）的城市
    cities.value = cityData.filter(city => city.status === 1)
  } catch (error) {
    ElMessage.error('加载城市列表失败: ' + error.message)
    cities.value = []
  }
}

// 省份选择变化处理
const onProvinceChange = async (provinceId) => {
  formData.cityId = null
  cities.value = []
  
  if (provinceId) {
    await loadCities(provinceId)
  }
}

// 验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, message: '用户名至少2个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== formData.password) {
          callback(new Error('两次密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  cityId: [
    { required: true, message: '请选择居住城市', trigger: 'change' }
  ]
})

// 加载状态
const loading = ref(false)

// 提交注册
const onSubmit = async () => {
  try {
    const valid = await formRef.value.validate()
    if (!valid) {
      ElMessage.error('请检查表单输入')
      return
    }

    loading.value = true
    
    // 调用注册API
    const registerData = {
      username: formData.username,
      password: formData.password,
      phone: formData.phone,
      cityId: formData.cityId
    }
    
    await register(registerData)
    
    ElMessage.success('注册成功！')
    console.log('注册信息:', registerData)
    
    // 注册成功后跳转到登录页
    router.push('/login')
    
  } catch (error) {
    ElMessage.error('注册失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 跳转
const gotoLogin = () => router.push('/login');
const gotoForget = () => router.push('/forget');

// 组件挂载时加载省份列表
onMounted(() => {
  loadProvinces()
})

</script>

<style scoped>
/* === 完全复用 LoginView 的 UI 风格 === */
/* （样式同上，为节省篇幅省略，实际文件中请复制相同 style 块） */
/* 建议：可提取为全局 SCSS 变量文件，此处保持一致即可 */
</style>